//* when dummy is destroyed, it scatter few credits around

function Credit(ALeft,ATop) {
  // contructor for single credit
  this.life = 100+100*Math.random();
  this.x = ALeft;
  this.y = ATop;
  this.dx = 5*(Math.random()-Math.random());
  this.dy = 5*(Math.random()-Math.random());
  // draw function
  this.draw = function() {
    // age and move credit
    this.life--;
    this.x += this.dx;
    this.y += this.dy;
    this.dx *= 0.95;
    this.dy *= 0.95;
    
    // draw credit
    context.save();
    context.translate(this.x-x0-ship.x,this.y-y0-ship.y);
    context.fillStyle = "rgba(255,255,0,"+(0.1+0.9*this.life/100)+")";
    context.fillRect(-1,-1,2,2);
    context.restore();
  }
}

function Credits() {
  // handler of all credits
  this.credits = new Array();
  
  this.explode = function(ALeft,ATop,ACount) {
    // create bunch of credits
    // alert('Exploding '+ACount+' credits at ['+Math.round(ALeft)+', '+Math.round(ATop)+']');
    for (var i=0; i<ACount; i++)
      this.credits.push(new Credit(ALeft,ATop));
  }
  
  // draw function
  this.draw = function() {
    var eaten = 0;
    for (var i=this.credits.length-1; i>0; i--) {
      // draw
      this.credits[i].draw();
      // suck near credits into ship and increase it's credit
      /*
      context.fillStyle = "black";
      context.fillRect(4,15,200,50);
      context.fillStyle = "red";
      context.fillText("C="+Math.round(this.credits[i].x)+","+Math.round(this.credits[i].y)+"  S="+ship.x+","+ship.y,4,30);
      */
      var close = false;
      if ( (ship.life > 0)&&(eaten<ship.beams) )
        var close = (Math.abs(this.credits[i].x-ship.x) < ship.magnet) && (Math.abs(this.credits[i].y-ship.y) < ship.magnet);
      // remove old credits
      if ( (this.credits[i].life <= 0)||close ) {
        if (close) {
          ship.credit += ship.credit_multiplier;
          context.lineWidth = 4;
          context.strokeStyle = "rgba(200,200,255,0.3)";
          context.beginPath();
          context.moveTo(-x0,-y0);
          context.lineTo(-x0+this.credits[i].x-ship.x,-y0+this.credits[i].y-ship.y);
          context.stroke();
          context.closePath();
        }
        this.credits.splice(i,1);
        eaten++;
      }
    }
      
  }   
}
